/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.biblioteca.controller;

import br.com.biblioteca.dao.DAOFacade;
import br.com.biblioteca.dao.IBookDAO;
import br.com.biblioteca.dao.ILoanDAO;
import br.com.biblioteca.exceptions.BadRequestException;
import br.com.biblioteca.utils.ServletUtils;
import br.com.biblioteca.vo.Book;
import br.com.biblioteca.vo.Loan;
import br.com.biblioteca.vo.User;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;

/**
 *
 * @author joaosavio
 */
public class BookService implements IService {

    public enum Action {
        borrowBook, returnBook, listAvaliableBooks, listBorrowedBooks
    }

    public void execute(ServiceRequestTO serviceRequestTO) throws Exception {
        if (serviceRequestTO.getAction().equals(Action.borrowBook.toString())) {
            borrow(serviceRequestTO.getRequest(), serviceRequestTO.getResponse());
            return;
        }
        if (serviceRequestTO.getAction().equals(Action.returnBook.toString())) {
            returnBook(serviceRequestTO.getRequest(), serviceRequestTO.getResponse());
            return;
        }
        if (serviceRequestTO.getAction().equals(Action.listAvaliableBooks.toString())) {
            listAvaliableBooks(serviceRequestTO.getRequest(), serviceRequestTO.getResponse());
            return;
        }
        if (serviceRequestTO.getAction().equals(Action.listBorrowedBooks.toString())) {
            listBorrowedBooks(serviceRequestTO.getRequest(), serviceRequestTO.getResponse());
            return;
        }
        throw new BadRequestException("Unknown action");
    }

    // You have to pass the book id in the parameter "bookId"
    private void borrow(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute("user");
        IBookDAO bookDAO = (IBookDAO) DAOFacade.getDAO(Book.class);
        String bookId = request.getParameter(Page.BOOK_ID_PARAMETER);
        if (StringUtils.isEmpty(bookId)) {
            throw new BadRequestException("Book id mismatch");
        }
        long id = Long.valueOf(bookId);
        Book book = bookDAO.getById(id);
        Loan loan = new Loan(user, book);
        ILoanDAO loanDAO = (ILoanDAO) DAOFacade.getDAO(Loan.class);
        loanDAO.add(loan);

        book.setBorrowed(1);
        long loanSum = book.getLoanSum();
        book.setLoanSum(++loanSum);
        bookDAO.update(book);

        ServletUtils.dispatcher(request, response, Page.MAIN);
    }

    // You have to pass the book id in the parameter "bookId"
    private void returnBook(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute("user");
        IBookDAO bookDAO = (IBookDAO) DAOFacade.getDAO(Book.class);
        String bookId = request.getParameter(Page.BOOK_ID_PARAMETER);
        if (StringUtils.isEmpty(bookId)) {
            throw new BadRequestException("Book id mismatch");
        }
        long id = Long.valueOf(bookId);
        Book book = bookDAO.getById(id);
        Loan loan = new Loan(user, book);
        ILoanDAO loanDAO = (ILoanDAO) DAOFacade.getDAO(Loan.class);
        loanDAO.delete(loan);

        book.setBorrowed(0);
        bookDAO.update(book);
        
        ServletUtils.dispatcher(request, response, Page.MAIN);
    }

    private void listAvaliableBooks(HttpServletRequest request, HttpServletResponse response) throws IOException {
        IBookDAO bookDAO = (IBookDAO) DAOFacade.getDAO(Book.class);
        List<Book> result = bookDAO.listAll();
        List<Book> list = new ArrayList<Book>();
        for (int i = 0; i < result.size(); i++) {
            if (result.get(i).getBorrowed() == 0) {
                list.add(result.get(i));
            }
        }
        response.setContentType("text/html; charset=UTF-8");
        setTableToBorrow(list, response.getWriter());
        //ServletUtils.dispatcher(request, response, Page.BOOKS_AVALIABLE);
    }

    private void listBorrowedBooks(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ILoanDAO loanDAO = (ILoanDAO) DAOFacade.getDAO(Loan.class);
        List<Loan> result = loanDAO.listAll();
        List<Book> list = new ArrayList<Book>();
        
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute("user");
        
        for (int i = 0; i < result.size(); i++) {
            if (result.get(i).getLoanPK().getUser().getLogin().equals(user.getLogin()) && result.get(i).getLoanPK().getBook().getBorrowed() == 1) {
                list.add(result.get(i).getLoanPK().getBook());
            }
        }
        response.setContentType("text/html; charset=UTF-8");
        setTableToReturn(list, response.getWriter());        
    }

    private void setTableToBorrow(List<Book> list, PrintWriter out) {
        out.println("<html><head><title>Books</title></head><body>");
        out.println("<h1>Books found</h1>");
        out.println("<table>");
        out.println("<tr>");
        out.println("<th>ISBN</th>");
        out.println("<th>Title</th>");
        out.println("<th>Autor</th>");
        out.println("<th>Editora</th>");
        out.println("<th>Action</th>");
        out.println("</tr>");
        for (int i = 0; i < list.size(); i++) {
            out.println("<tr>");
            out.println("<td>");
            out.println(list.get(i).getIsbn());
            out.println("</td>");
            out.println("<td>");
            out.println(list.get(i).getTitle());
            out.println("</td>");
            out.println("<td>");
            out.println(list.get(i).getAutor());
            out.println("</td>");
            out.println("<td>");
            out.println(list.get(i).getEditora());
            out.println("</td>");
            out.println("<td>");
            String link = "<a href=\"http://localhost:8080/biblioteca/logic?service=BookService&action=borrowBook&bookId="+list.get(i).getId()+"\">BORROW</a>";
            out.println(link);
            out.println("</td>");
            out.println("</tr>");
        }
        out.println("</table>");
        out.println("</body></html>");
        out.close();
    }

    private void setTableToReturn(List<Book> list, PrintWriter out) {
        out.println("<html><head><title>Books</title></head><body>");
        out.println("<h1>Books found</h1>");
        out.println("<table>");
        out.println("<tr>");
        out.println("<th>ISBN</th>");
        out.println("<th>Title</th>");
        out.println("<th>Autor</th>");
        out.println("<th>Editora</th>");
        out.println("<th>Action</th>");
        out.println("</tr>");
        for (int i = 0; i < list.size(); i++) {
            out.println("<tr>");
            out.println("<td>");
            out.println(list.get(i).getIsbn());
            out.println("</td>");
            out.println("<td>");
            out.println(list.get(i).getTitle());
            out.println("</td>");
            out.println("<td>");
            out.println(list.get(i).getAutor());
            out.println("</td>");
            out.println("<td>");
            out.println(list.get(i).getEditora());
            out.println("</td>");
            out.println("<td>");
            String link = "<a href=\"http://localhost:8080/biblioteca/logic?service=BookService&action=returnBook&bookId="+list.get(i).getId()+"\">RETURN</a>";
            out.println(link);
            out.println("</td>");
            out.println("</tr>");
        }
        out.println("</table>");
        out.println("</body></html>");
        out.close();
    }
}
